//
//  BIZOfflineConsultRecordsVC.m
//  biz
//
//  Created by zhangfuwei on 2017/4/17.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZOfflineConsultRecordsVC.h"

// cell
#import "BIZNoConsultorCell.h"
#import "BIZOfflineConsultRecordsCell.h"
// vc
#import "BIZOfflineConsultQuestionVC.h"
#import "BIZOfflineConsultQuestionDetailVC.h"
// model
#import "BIZOfflineConsultRecordsModel.h"



static NSString *const kOfflineConsultRecordsReuseCellID = @"kOfflineConsultRecordsReuseCellID";
static NSString *const kNoSuitableConsultorCellID = @"kNoSuitableConsultorCellID";

@interface BIZOfflineConsultRecordsVC ()<UITableViewDelegate,UITableViewDataSource>

/** tableView */
@property (nonatomic, strong) UITableView *tableView;

/** 数据源的最后ID */
@property (nonatomic, assign) NSInteger lastId;

/** 咨询记录模型 */
@property (nonatomic, strong) BIZOfflineConsultRecordsModel *recordsModel;


@end

@implementation BIZOfflineConsultRecordsVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupConfig];
    [self addTableView];
    
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // MARK:TO DO 刷新数据
    _lastId = 1;
    [self requestOfflineConsultRecords];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 视图加载

- (void)setupConfig {
    
    _lastId = 1;

    self.view.backgroundColor = HEXCOLOR(0xf9f9f9);

    UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 62, 15)];
    titleLab.textColor = [UIColor whiteColor];
    titleLab.font = CHINESE_SYSTEM(16);
    titleLab.text = @"线下咨询记录";
    self.navigationItem.titleView = titleLab;
    
    // MARK:TO DO 我要线下咨询

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 85, 14)];
    [btn setTitle:@"我要线下咨询" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    btn.titleLabel.font = CHINESE_SYSTEM(14);
    [btn addTarget:self action:@selector(rightBarButtonItemClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
}

- (void)addTableView {
    CGRect tableViewFrame = CGRectMake(0, 0, Main_Screen_Width, self.view.bounds.size.height-BIZNavgationBarH);
    self.tableView = [[UITableView alloc] initWithFrame:tableViewFrame style:UITableViewStylePlain];
    self.tableView.backgroundColor = HEXCOLOR(0xf9f9f9);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.tableFooterView = [UIView new];
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 10)];
    grayView.backgroundColor = HEXCOLOR(0xf9f9f9);
    self.tableView.tableHeaderView = grayView;
    [self.tableView registerClass:[BIZOfflineConsultRecordsCell class] forCellReuseIdentifier:kOfflineConsultRecordsReuseCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"BIZNoConsultorCell" bundle:nil] forCellReuseIdentifier:kNoSuitableConsultorCellID];
    
    self.tableView.estimatedRowHeight = 30;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewest)];
    self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreHistory)];
    
    [self.view addSubview:self.tableView];
}



#pragma mark -- 网络请求
- (void)requestOfflineConsultRecords {
    [RequestTool POST:kOfflineConsultRecordsURL
           parameters:@{@"pageIndex" : @(_lastId), @"pageEnd" : @(_lastId + 9)}
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"线下咨询记录--%@",responseObject);
                  [self stopRefresh];
                  BIZOfflineConsultRecordsModel *recordsModel = [BIZOfflineConsultRecordsModel yy_modelWithJSON:responseObject];
                  if (recordsModel.code.intValue == 1) {
                      if (_lastId == 1) {
                          self.recordsModel = recordsModel;
                      }else{
                          
                          self.recordsModel.data = [self.recordsModel.data arrayByAddingObjectsFromArray:recordsModel.data];
                      }
                      _lastId += (int)recordsModel.data.count;
                      [self.tableView reloadData];

                  }else if (recordsModel.code.intValue == 2){
                      [MBProgressHUD showTipMessageInView:@"请登录"];
                      [BIZUserModel shareUser].login = NO;
                      [self presentViewController:[BIZLoginViewController viewControllerFromStoryboard] animated:YES completion:nil];
                      
                  }else{
                      
                      [MBProgressHUD showErrorMessage:recordsModel.des];
                  }
                  
              }
              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  [self stopRefresh];
                  [MBProgressHUD showErrorMessage:@"网络不给力,请检测网络" timer:2.5];
                  DeLog(@"error ---%@",error);
                  
              }
     ];

}

#pragma mark -- 代理方法/数据源

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.recordsModel.data.count) {
        
        return self.recordsModel.data.count;
        
    }else{
        return 1;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.recordsModel.data.count) {
        
        BIZOfflineConsultRecordsCell *cell = [tableView dequeueReusableCellWithIdentifier:kOfflineConsultRecordsReuseCellID forIndexPath:indexPath];
        
        BIZOfflineConsultRecordsDataModel *dataM = self.recordsModel.data[indexPath.row];
        
        cell.dataModel =  dataM;
        return cell;
    }else{
        
        BIZNoConsultorCell *cell = [tableView dequeueReusableCellWithIdentifier:kNoSuitableConsultorCellID forIndexPath:indexPath];
        cell.errorMsg = @"暂无线下咨询记录";
        return cell;
    }
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BIZOfflineConsultRecordsDataModel *dataM = self.recordsModel.data[indexPath.row];
    BIZOfflineConsultQuestionDetailVC *queDetailVC = [[BIZOfflineConsultQuestionDetailVC alloc] initWithQuestionUuid:dataM.uuid];
    
    [self.navigationController pushViewController:queDetailVC animated:YES];
    
}



#pragma mark -- 私有方法

- (void)rightBarButtonItemClick:(UIButton *)btn {
    BIZOfflineConsultQuestionVC *questionVC = [[BIZOfflineConsultQuestionVC alloc] init];
    
    [self.navigationController pushViewController:questionVC animated:YES];
}

- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}


- (void)loadNewest {
    _lastId = 1;
    [self requestOfflineConsultRecords];
}

- (void)loadMoreHistory {
    [self requestOfflineConsultRecords];
}


@end
